<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2017/3/29
 * Time: 17:22
 */

namespace App\Api\V1\Controllers;

use App\Models\User\UAddress;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;

class AreaController extends BaseController
{
    public function getArea()
    {

    }

    public function info()
    {
        $request = Request::all();
        $id = $request['id'];
        $uaddress = UAddress::where('user_id', \Auth::id())->where("id", $id)->first();
        return $this->response->array($uaddress);
    }

    public function put()
    {

        $request = Request::all();
        $validator = Validator::make($request, [
            'nickname' => 'required',
            'phone' => 'required',
            'address_info' => 'required',
            'province' => 'required',
            'city' => 'required',
            'area' => 'required',
        ], [
            'nickname.required' => '请输入名称',
            'phone.required' => '请输入联系电话',
        ]);
        if ($validator->fails()) {
            return $this->response->array(['message' => $validator->errors()->first(), 'status_code' => 0]);
        } else {
            $id = $request['address_id'];
            $user = \Auth::user();
            if ($id > 0) {
                $uaddress = UAddress::where('user_id', $user->id)->where("id", $id)->first();
                $uaddress->nickname = $request['nickname'];
                $uaddress->phone = $request['phone'];
                $uaddress->province = $request['province'];
                $uaddress->city = $request['city'];
                $uaddress->area = $request['area'];
                $uaddress->address = $request['address_info'];
                $uaddress->save();
            } else {
                $count = UAddress::where(['user_id' => $user->id])->count();
                if ($count >= 10) {
                    return $this->response->array(['message' => '最多添加10条哦', 'status_code' => 0]);
                }
                $uaddress = new UAddress();
                $uaddress->nickname = $request['nickname'];
                $uaddress->phone = $request['phone'];
                $uaddress->province = $request['province'];
                $uaddress->city = $request['city'];
                $uaddress->area = $request['area'];
                $uaddress->address = $request['address_info'];
                $uaddress->user_id = $user->id;
                $uaddress->save();
            }


            return $this->response->array(['message' => '保存成功', 'status_code' => 200]);

        }
    }
}